﻿using System;
using System.Collections.Generic;
using UnityEngine;
using WooEngine.Utility.Random;
using WooEngine.Utility.Security.Base;

namespace WooEngine.ConfigWork.Table
{
    public abstract class ProtoTable <T>  where T : ProtoDataBase 
    {
        protected Dictionary<EncryptInt, T> itemMap = new Dictionary<EncryptInt, T>();

        public virtual void LoadData()
        {

        }

        protected void initWithData(ConfigFileData data)
        {
            foreach(var key in data.Key_dic)
            {
                T ins = Activator.CreateInstance<T>();
                EncryptInt keyInt = int.Parse(key.Key);
                ins.init(keyInt, data.Data[key.Value].list.ToArray());
                this.itemMap.Add(keyInt, ins);

            }
        }

        public T getByKey(EncryptInt key)
        {
            return this.itemMap[key];
        }

        public bool hasByKey(EncryptInt key)
        {
            return this.itemMap.ContainsKey(key);
        }

        public Dictionary<EncryptInt, T> ItemMap
        {
            get
            {
                return this.itemMap;
            }
        }

        public virtual void Clear()
        {
            this.itemMap.Clear();
        }

        public int Count
        {
            get
            {
                return ItemMap.Count;
            }
        }

        public T RandomItem()
        {
            int i = RTGameRandomUtils.RandomInt(Count);
            foreach(T item in itemMap.Values)
            {
                if(i == 0)
                {
                    return item;
                }
                i--;
            }
            return null;
        }
    }
}
